package com.itheima.mapper;

import com.itheima.domain.*;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

/*
    使用注解实现 多表查询 一对一 一对多 多对多
 */
public interface Some2SomeMapper {

    //一对一 person对card查询
    @Select("select * from person")
    @Results({
            //和映射配置文件的字段一样 格式有点差异
            @Result(id = true, column = "id", property = "id"), //属性id为真
            @Result(column = "name", property = "name"),
            @Result(column = "age", property = "age"),
            //写关联查询的对象
            @Result(
                    property = "c",             //被包含对象的变量名
                    javaType = Card.class,      //被包含对象的实际数据类型
                    column = "id",              //根据查询出的表中id字段来查询关联表  此处通过person.id查询card的pid
                    /*
                        one @One 一对一固定写法
                        select: 指定调用哪个接口中的哪个方法
                     */
                    one = @One(select = "com.itheima.mapper.Some2SomeMapper.findCardById")
            )
    })
    List<Person> findAll();

    //一对多 班级classes对student查询
    @Select("select * from classes")
    @Results(id = "classesMap", value = {
            @Result(id = true, column = "id", property = "id"),
            @Result(id = true, column = "name", property = "name"),
            @Result(
                    property = "stuList",      //被包含的对象集合名
                    javaType = List.class,     //被包含对象的类型
                    column = "id",             //需要传给关联表查询的参数
                    many = @Many(select = "com.itheima.mapper.Some2SomeMapper.findStuById", fetchType = FetchType.LAZY)
                    //一对多查询 select: 调用方法的全限定类名, 一对多,推荐使用延迟加载
            )
    })
    List<Classes> findClasses();

    //多对多 student对course查询
    @Select("select * from student")
    @Results(id = "studentMap", value = {
            @Result(id = true, column = "id", property = "id"),
            @Result(column = "name", property = "name"),
            @Result(column = "age", property = "age"),
            @Result(
                    property = "courses",   //被包含对象名
                    javaType = List.class,  //被包含对象类型
                    column = "id",         //传给关联表查询的参数
                    many = @Many(select = "com.itheima.mapper.Some2SomeMapper.findCourseById")
                    //对多 指定调用接口的方法全限定类名
            )
    })
    List<Student> findStudents();

    //通过student.id获取 stu_cr表中的课程编号, 再获取到课程并返回
    @Select("select * from stu_cr sc,course c where sc.cid=c.id and sc.sid=#{sid}")
    List<Course> findCourseById(@Param("sid") Integer sid);

    //通过card.id获取Card
    @Select("select * from card where pid=#{pid}")
    Card findCardById(@Param("pid") Integer pid);

    //通过班级classes.id 获取Student列表
    @Select("select * from student where cid=#{cid}")
    List<Student> findStuById(@Param("cid") Integer cid);


}
